﻿#include "pingmodel.h"

#include <QCoreApplication>
#include <QProcess>
#include <QTextCodec>
#include <QDebug>
#include <stdio.h>
#include <QThread>
#include <ttcclayout.h>
#include <consoleappender.h>
#include <rollingfileappender.h>

#include "log4qt.h"
#include "log4qt/basicconfigurator.h"
#include "log4qt/logger.h"
#include "log4qt/propertyconfigurator.h"
#include "log4qt/logmanager.h"
#include "log4qt/loggerrepository.h"
#include <CoreWindow.h>
#include <QUdpSocket>

static void ternimate(QCoreApplication &a);
static void setupRootLogger();
static void shutdownRootLogger();

static QUdpSocket *udp1;

QHostAddress host;
int serverPort,localPort;

PingModel *model;
void sendData(QByteArray data){

        if(udp1!=NULL){
                udp1->writeDatagram(data,host,serverPort);
        }
}

void initUdp(QCoreApplication &a){

        udp1 = new QUdpSocket;
        udp1->bind(localPort);
//        host = QHostAddress(QHostAddress::LocalHost);
        host = QHostAddress("127.0.0.1");

        qDebug()<<"localPort: "<<localPort<<" serverPort: "<<serverPort;

        //发送数据
        sendData(QString("CLIENTMSG###"+a.applicationName()+":"+QString::number(localPort)+" started").toUtf8());

        //接收数据
        QObject::connect(udp1,&QUdpSocket::readyRead,[&](){
                QByteArray array(udp1->pendingDatagramSize(),0);
                udp1->readDatagram(array.data(),array.length());

                qDebug()<<"readyRead: "<<array;

                QString head = QString(array).section("###",0,0);
                QString type = QString(array).section("###",1,1).toUpper();
                QString msg = QString(array).section("###",2,2);
                qDebug()<<"headddd: "<< head <<"\r\ntypeeee: "<< type <<"\r\nmsgggg: "<< msg;

                if(head=="SERVERMSG"){
                        if(type=="TERMINATE"){
                                ternimate(a);
                        }
                }
                else {
                    qDebug()<<"headddddddddddddddd: "<<head;
                }
        });
}

void ternimate(QCoreApplication &a){
        model->exit();
        qDebug() << "Terminou o processo.";
        shutdownRootLogger();
        sendData(QString("CLIENTMSG###TERMINATE###"+a.applicationName() +"###TERMINATED...").toUtf8());
}

int main(int argc, char *argv[])
{
        QCoreApplication a(argc, argv);

        //    qDebug()<< argc;
        //    qDebug()<< argv[0];
        //    qDebug()<< argv[1];
        //    qDebug()<< argv[2];

        //    //修改进程优先级 https://blog.csdn.net/weixin_43229139/article/details/119535174
        //    SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);

        setupRootLogger();

        if(argc>1){
                serverPort = QString(argv[1]).toInt();
                localPort = QString(argv[2]).toInt();
                if(serverPort>=9000&&localPort>serverPort){
                        initUdp(a);
                }
        }


        qDebug() << "Iniciando o ping ...";
        model = new PingModel;
        model->start_command("www.baidu.com");

        while(model->is_running()){
                qDebug() << "waiting ...";
                QThread::sleep(1);
        }

//        ternimate(a);

        return 1;
}


void setupRootLogger()
{
        // Create a layout
        auto logger = Log4Qt::Logger::rootLogger();
        auto *layout = new Log4Qt::TTCCLayout();
        // Set level to info
        logger->setLevel(Log4Qt::Level::ALL_INT);
        // Enable handling of Qt messages
        Log4Qt::LogManager::setHandleQtMessages(true);

        layout->setDateFormat("[yyyy-mm-dd HH:MM:ss]");
        layout->setName(QStringLiteral("My Layout"));
        layout->activateOptions();

        // Create a console appender
        Log4Qt::ConsoleAppender *consoleAppender = new Log4Qt::ConsoleAppender(layout, Log4Qt::ConsoleAppender::STDOUT_TARGET);
        consoleAppender->setName(QStringLiteral("My Appender"));
        consoleAppender->activateOptions();
        // Add appender on root logger
        logger->addAppender(consoleAppender);


        Log4Qt::RollingFileAppender *appender = new Log4Qt::RollingFileAppender;
        // 设置输出目的地为应用程序所在目录下的logFile.log
        appender->setFile("A.log");
        // 设置日志为追加方式写入输出文件
        appender->setAppendFile(true);
        // 设置备份文件的最大数量为10个
        appender->setMaxBackupIndex(2);
        // 设置输出文件的最大值为1KB
        appender->setMaxFileSize("1KB");
        appender->setLayout(layout);
        // 设置编码
        appender->setEncoding(QTextCodec::codecForName("UTF-8"));

        appender->setImmediateFlush(true);
        // 设置阈值级别为INFO
        appender->setThreshold(Log4Qt::Level::ALL_INT);
        // 激活选项
        appender->activateOptions();
        logger->addAppender(appender);


        qWarning("Handling Qt messages is enabled");
}

void shutdownRootLogger()
{
        auto logger = Log4Qt::Logger::rootLogger();
        logger->removeAllAppenders();
        logger->loggerRepository()->shutdown();
}
